import axios, { AxiosResponse, AxiosRequestConfig } from 'axios';
import { ElMessageBox, ElMessage } from 'element-plus';
import storage from '@/utils/storage';
// const isServer = import.meta.env.MODE; // production
const service = axios.create({
    baseURL: import.meta.env.VITE_BASE_URL, // 获取环境变量配置
    timeout: 10000, // 设置超时时间
}); // Request interceptor
// 自定义传入的参数
service.interceptors.request.use(
    (config: any) => {
        const { url, contentType } = config;
        const users: any = storage.get('user');
        if (storage.get('token')) {
            config.headers = {
                Authorization: 'Bearer ' + storage.get('token'),
                operId: users?.OperId,
                operName: encodeURIComponent(users?.OperName),
                operType: encodeURIComponent(users?.OperType),
            };
        }
        if (
            config.url === '/api/v1/atsAdminApp/upload' ||
            config.url === '/api/v1/atsAdminApp/meta/uploadUserLabelsRel'
        ) {
            config.headers['Content-Type'] = 'multipart/form-data';
        } else {
            config.headers['Content-Type'] = 'application/json';
        }
        return config;
    },
    (error: any) => {
        Promise.reject(error);
    }
); // Response interceptors

service.interceptors.response.use(
    async (response: AxiosResponse) => {
        const code = response.data.code;
        if (code === 401) {
            storage.remove('token');
            sessionStorage.clear();
            if (window.location.href.indexOf('login') != -1) {
                window.location.reload(); // 为了重新实例化vue-router对象 避免bug
            } else {
                ElMessageBox.confirm(
                    '登录状态已过期，您可以继续留在该页面，或者重新登录',
                    '系统提示',
                    {
                        confirmButtonText: '重新登录',
                        cancelButtonText: '取消',
                        type: 'warning',
                    }
                ).then(() => {
                    window.location.reload(); // 为了重新实例化vue-router对象 避免bug
                });
            }
        } else if (code === 6401) {
            storage.remove('token');
            sessionStorage.clear();
            ElMessageBox.confirm(
                '登录状态已过期，您可以继续留在该页面，或者重新登录',
                '系统提示',
                {
                    confirmButtonText: '重新登录',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            ).then(() => {
                window.location.reload(); // 为了重新实例化vue-router对象 避免bug
            });
            return false;
        } else if (code === 400 || code === 403) {
            storage.remove('token');
            sessionStorage.clear();
            ElMessage({
                message: response.data.msg,
                type: 'error',
                duration: 5 * 1000,
            });
        } else {
            return response.data;
        }
    },
    (error: any) => {
        console.log(error);
        if (error.message == 'Network Error') {
            ElMessage({
                message: '服务器连接异常，请检查服务器！',
                type: 'error',
                duration: 5 * 1000,
            });
            return;
        }
        // console.log(error.response.data.message);
        ElMessage({
            message: error.response.data.message,
            type: 'error',
            duration: 5 * 1000,
        });

        return Promise.reject(error);
    }
);

export default service;
